package com.lyj.validates.validates;

import com.lyj.validates.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import com.google.common.base.Strings;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.*;
import java.util.Date;

/**
 * 时间属性格式校验
 * @author:liyajie
 * @createTime:2022/1/20 10:38
 * @version:1.0
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER,ElementType.FIELD})
@Constraint(validatedBy = DateValidator.Validator.class)
public @interface DateValidator {
    // 校验未通过时的返回信息
    String message() default "日期格式不正确";

    // 以下两行为固定模板
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
    /**
     * 预期日期格式
     */
    String expectValue();

    @Slf4j
    class Validator implements ConstraintValidator<DateValidator, String> {

        private String expectValue;

        @Override
        public void initialize(DateValidator dateValidator) {
            expectValue = dateValidator.expectValue();
        }

        @Override
        public boolean isValid(String value, ConstraintValidatorContext context) {
            boolean flag = false;
            /**
             * 为空直接通过，只做格式验证
             */
            if(Strings.isNullOrEmpty(value)){
                return true;
            }
            try {
                Date date = DateUtil.formatStr2Date(value, expectValue);
                flag = true;
            }catch (RuntimeException e){
                log.warn("DateValidator 日期格式不正确");
                e.printStackTrace();
            }
            return flag;
        }
    }
}
